<template>
  <div>
    <!-- 课时定价 -->
    <div>
      <div class="m-h2-btn-box">
        <h2>定价规则</h2>
        <div class="u-btn-box">
          <el-button type="primary" v-if="!isSave" @click="edit()"
            >编辑</el-button
          >
          <el-button type="primary" v-else @click="save()">保存</el-button>
        </div>
      </div>
      <div class="m-form-box">
        <el-row>
          <el-col :span="6">
            <b class="u-b-title">初始价格(元)</b>
            <div class="grid-content bg-purple">
              <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item
                  v-for="(item, index) in type_list"
                  :key="index"
                  :label="setSelectObj(item.course_type)"
                >
                  <div class="z-flex">
                    <el-input
                      type="number"
                      min="0"
                      v-model="item.price"
                      oninput="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                      :disabled="!isSave"
                      placeholder="请输入价格(单位/元)"
                    ></el-input>
                    <div class="u-delete-box" v-if="isSave">
                      <el-popconfirm
                        title="确认要删除该项？"
                        @onConfirm="deleteForm('课程类型', item, index)"
                      >
                        <i
                          class="el-icon-delete margin-top5"
                          slot="reference"
                        ></i>
                      </el-popconfirm>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item v-if="isSave">
                  <el-button
                    type="primary"
                    @click="addDataFn('课程类型')"
                    icon="el-icon-plus"
                    class="u-add-btn"
                    circle
                  ></el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
          <el-col :span="6">
            <b class="u-b-title">年级溢价(元)</b>
            <div class="grid-content bg-purple-light">
              <el-form
                :model="ruleForm2"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item
                  v-for="(item, index) in stage_list"
                  :key="index"
                  :label="setSelectObj(item.stage_type)"
                  prop="val"
                >
                  <div class="z-flex">
                    <el-input
                      v-model="item.price"
                      type="number"
                      min="0"
                      oninput="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                      :disabled="!isSave"
                      placeholder="请输入价格(单位/元)"
                    ></el-input>
                    <div class="u-delete-box" v-if="isSave">
                      <el-popconfirm
                        title="确认要删除该项？"
                        @onConfirm="deleteForm('年级类型', item, index)"
                      >
                        <i
                          class="el-icon-delete margin-top5"
                          slot="reference"
                        ></i>
                      </el-popconfirm>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item v-if="isSave">
                  <el-button
                    type="primary"
                    @click="addDataFn('年级类型')"
                    icon="el-icon-plus"
                    class="u-add-btn"
                    circle
                  ></el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
          <el-col :span="6">
            <b class="u-b-title">讲师等级溢价(元)</b>
            <div class="grid-content bg-purple">
              <el-form
                :model="ruleForm3"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item
                  v-for="(item, index) in teacher_list"
                  :key="index"
                  :label="setSelectObj(item.level_type)"
                  prop="val"
                >
                  <div class="z-flex">
                    <el-input
                      v-model="item.price"
                      type="number"
                      min="0"
                      oninput="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
                      :disabled="!isSave"
                      placeholder="请输入价格(单位/元)"
                    ></el-input>
                    <div class="u-delete-box" v-if="isSave">
                      <el-popconfirm
                        title="确认要删除该项？"
                        @onConfirm="deleteForm('讲师等级', item, index)"
                      >
                        <i
                          class="el-icon-delete margin-top5"
                          slot="reference"
                        ></i>
                      </el-popconfirm>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item v-if="isSave">
                  <el-button
                    type="primary"
                    @click="addDataFn('讲师等级')"
                    icon="el-icon-plus"
                    class="u-add-btn"
                    circle
                  ></el-button>
                </el-form-item>
              </el-form>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <div>
      <h2>价格详情</h2>
      <el-table
        :data="tableData"
        style="width: 100%"
        :span-method="objectSpanMethod"
        header-cell-class-name="thead"
      >
        <!-- span-method="objectSpanMethod" header-cell-class-name="thead" -->
        <!-- <el-table :data="tableData" style="width: 100%"> -->

        <el-table-column
          v-for="(item, index) in tableTitle"
          :key="index"
          :prop="item"
          :label="setSelectObj(item, 'title')"
          width="180"
        >
          <template slot-scope="scope">{{
            setSelectObj(scope.row[item])
          }}</template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增对话框 -->
    <el-dialog
      :title="'新增' + addDataTitle"
      :visible.sync="addDataShow"
      width="30%"
    >
      <el-form
        label-width="100px"
        :model="addForm"
        :rules="rules2"
        ref="ruleForm2"
      >
        <el-form-item :label="addDataTitle" prop="addDataVal">
          <el-input
            v-model="addForm.addDataVal"
            :placeholder="getPlaceholder()"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格">
          <el-input
            type="number"
            min="0"
            oninput="this.value=this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3')"
            placeholder="请输入价格(单位/元)"
            v-model="addForm.price"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="addNow()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { queryList } from '@/api/api.js'
import {
  qryCoursePriceDetails,
  updateCoursePricing,
  insertStagePrice,
  insertTypePrice,
  insertTeacherPrice,
  deleteStagePrice,
  deleteTypePrice,
  deleteTeacherPrice
} from '@/api/course.js'
export default {
  data () {
    return {
      addForm: {
        addDataVal: '',
        price: ''
      },
      addDataTitle: '',
      addDataShow: false,
      isSave: false,
      tableData: [],
      ruleForm: {
        count: 1,
        name_0: '正价课',
        val_0: ''
      },
      ruleForm2: { count: 1, name_0: '小学老师', val_0: '' },
      ruleForm3: { count: 1, name_0: '初级讲师', val_0: '' },
      rules: {
        val_0: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
        ]
      },
      rules2: {
        addDataVal: [
          { required: true, message: '请输入新增类型', trigger: 'blur' }
        ]
      },
      tableTitle: [],
      seleteObj: {},
      type_list: [],
      stage_list: [],
      teacher_list: [],
      lastIndex: 0,
      formParent: [
        {
          quety: 'nice_course_type_price',
          parent: 44
        },
        {
          quety: 'nice_course_stage_price',
          parent: 412
        },
        {
          quety: 'nice_course_teacher_level_price',
          parent: 234
        }
      ]
    }
  },
  created () {
    this.getTableSelete()
  },
  methods: {
    getPlaceholder () {
      if (this.addDataTitle === '课程类型') {
        return '请输入课程类型名称'
      }
      if (this.addDataTitle === '年级类型') {
        return '请输入年级类型名称 '
      } else {
        return '请输入讲师等级'
      }
    },
    oninput (e) {
      e.target.value = e.target.value.match(/^\d*(\.?\d{0,2})/g)[0] || null
    },
    // 过滤枚举
    setSelectObj (e, title) {
      if (typeof e === 'string') {
        if (e === 'teacher_type' || e === 'stage_type' || title) {
          return this.seleteObj[e]
        } else {
          return e
        }
      } else {
        return this.seleteObj[e]
      }
    },
    // 获取枚举
    async getTableSelete () {
      this.seleteObj = {}
      let res = await queryList({
        parent: '412', // 学段
        table_name: 'nice_enum_tree'
      })
      if (res[0]) {
        return
      }
      let arr = [].concat(res[1].data)
      let res2 = await queryList({
        parent: '44', // 正价
        table_name: 'nice_enum_tree'
      })
      if (res[0]) {
        return
      }
      arr = arr.concat(res2[1].data)
      let res3 = await queryList({
        parent: '234', // 教师等级
        table_name: 'nice_enum_tree'
      })
      if (res[0]) {
        return
      }
      arr = arr.concat(res3[1].data)
      arr.map(item => {
        this.seleteObj[item.t_id] = item.display_value
      })
      this.seleteObj.teacher_type = '讲师等级'
      this.seleteObj.stage_type = '学段'
      this.getTableData()
    },
    // 获取整张页面数据
    async getTableData () {
      let res = await qryCoursePriceDetails({})
      if (res[0]) {
        return
      }
      this.tableData = res[1].data.price_details_List
      this.tableTitle = []
      for (let i in this.tableData[0]) {
        this.tableTitle.push(i)
      }
      let b = this.tableTitle.indexOf('teacher_type')
      this.tableTitle.unshift(this.tableTitle.splice(b, 1)[0])
      let a = this.tableTitle.indexOf('stage_type')
      this.tableTitle.unshift(this.tableTitle.splice(a, 1)[0])
      this.lastIndex = 0
      for (let i = 0; i < this.tableData.length; i++) {
        if (i === 0) {
          this.tableData[i].count = 1
          continue
        }
        if (
          this.tableData[i - 1].stage_type &&
          this.tableData[i].stage_type === this.tableData[i - 1].stage_type
        ) {
          this.tableData[i].count = 0
          this.lastIndex += 1
          this.tableData[i - this.lastIndex].count += 1
        } else {
          this.lastIndex = 0
          this.tableData[i].count = 1
        }
      }
      console.log(this.tableData[0])
      this.type_list = res[1].data.type_list
      this.stage_list = res[1].data.stage_list
      this.teacher_list = res[1].data.teacher_list
    },
    closeDialog () {
      this.$refs.ruleForm2.clearValidate()
      this.addDataShow = false
      this.addForm.addDataVal = ''
      this.addForm.price = ''
    },
    // 添加
    addNow () {
      //
      this.$refs.ruleForm2.validate(valid => {
        if (valid) {
          this.$refs.ruleForm2.clearValidate()
          if (parseInt(this.addForm.price) <= 0) {
            this.$message({
              message: '价格需大于0',
              type: 'warning'
            })
            return
          }
          switch (this.addDataTitle) {
            case '课程类型':
              this.typeAdd()
              // this.ruleForm[
              //   'name_' + this.ruleForm.count
              // ] = this.addForm.addDataVal
              // this.ruleForm['val_' + this.ruleForm.count] = ''
              // this.rules['val_' + this.ruleForm.count] = [
              //   { required: true, message: '请输入价格', trigger: 'blur' },
              //   { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
              // ]
              // this.ruleForm.count += 1
              // console.log(this.ruleForm)
              break
            case '年级类型':
              this.stageAdd()
              // this.ruleForm2[
              //   'name_' + this.ruleForm2.count
              // ] = this.addForm.addDataVal
              // this.ruleForm2['val_' + this.ruleForm2.count] = ''
              // this.ruleForm2.count += 1

              break
            case '讲师等级':
              this.teacherAdd()
              break
          }
          this.addForm.addDataVal = ''
          this.addForm.price = ''
          this.addDataShow = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 添加课程类型
    async typeAdd () {
      console.log(parseFloat(this.addForm.price))
      let res = await insertTypePrice({
        'nice_enum_tree.display_value': this.addForm.addDataVal,
        'nice_enum_tree.parent': 44,
        'nice_course_type_price.price': parseFloat(this.addForm.price)
      })
      if (res[0]) {
        return
      }

      // this.seleteObj[res[1].data.t_id] = this.addForm.addDataVal
      // this.type_list.push({price: this.addForm.price, stage_type: res[1].data.t_id})
      this.getTableSelete()
    },
    // 添加讲师等级
    async teacherAdd () {
      let res = await insertTeacherPrice({
        'nice_enum_tree.display_value': this.addForm.addDataVal,
        'nice_enum_tree.parent': 234,
        'nice_course_teacher_level_price.price': parseFloat(this.addForm.price)
      })
      if (res[0]) {
        return
      }
      // this.seleteObj[res[1].data.t_id] = this.addForm.addDataVal
      // this.teacher_list.push({price: this.addForm.price, level_type: res[1].data.t_id})
      this.getTableSelete()
    },
    // 添加年级类型
    async stageAdd () {
      let res = await insertStagePrice({
        'nice_enum_tree.display_value': this.addForm.addDataVal,
        'nice_enum_tree.parent': 412,
        'nice_course_stage_price.price': parseFloat(this.addForm.price)
      })
      if (res[0]) {
        return
      }
      // this.seleteObj[res[1].data.t_id] = this.addForm.addDataVal
      // this.stage_list.push({price: this.addForm.price, stage_type: res[1].data.t_id})
      this.getTableSelete()
    },
    // 删除课程类型
    async typeDelete (item, index) {
      console.log(item)
      let res = await deleteTypePrice({
        'nice_enum_tree.type_id': item.course_type,
        'nice_course_type_price.type_id': item.course_type
      })
      if (res[0]) {
        return
      }
      this.type_list.splice(index, 1)
    },
    // 删除年级类型
    async stageDelete (item, index) {
      let res = await deleteStagePrice({
        'nice_enum_tree.type_id': item.stage_type,
        'nice_course_stage_price.type_id': item.stage_type
      })
      if (res[0]) {
        return
      }
      this.stage_list.splice(index, 1)
    },
    // 删除讲师等级
    async teacherDelete (item, index) {
      console.log(item)

      let res = await deleteTeacherPrice({
        'nice_enum_tree.type_id': item.level_type,
        'nice_course_teacher_level_price.type_id': item.level_type
      })
      if (res[0]) {
        return
      }
      this.teacher_list.splice(index, 1)
    },
    deleteForm (e, item, index) {
      this.addDataTitle = e
      switch (this.addDataTitle) {
        case '课程类型':
          this.typeDelete(item, index)
          // this.ruleForm[
          //   'name_' + this.ruleForm.count
          // ] = this.addForm.addDataVal
          // this.ruleForm['val_' + this.ruleForm.count] = ''
          // this.rules['val_' + this.ruleForm.count] = [
          //   { required: true, message: '请输入价格', trigger: 'blur' },
          //   { min: 1, max: 5, message: '长度在 1 到 5 个字符', trigger: 'blur' }
          // ]
          // this.ruleForm.count += 1
          // console.log(this.ruleForm)
          break
        case '年级类型':
          // console.log(item, index)
          this.stageDelete(item, index)
          // this.ruleForm2[
          //   'name_' + this.ruleForm2.count
          // ] = this.addForm.addDataVal
          // this.ruleForm2['val_' + this.ruleForm2.count] = ''
          // this.ruleForm2.count += 1

          break
        case '讲师等级':
          this.teacherDelete(item, index)
          break
      }
    },
    addDataFn (e) {
      this.addDataTitle = e
      this.addDataShow = true
    },
    edit () {
      this.isSave = !this.isSave
    },
    async savequery () {
      let initPrice = []
      let gradePrice = []
      let levelPrice = []
      let num = false
      this.type_list.map(async item => {
        if (parseFloat(item.price) < 0) {
          num = true
          console.log(num, 1)
        }
        await initPrice.push(parseFloat(item.price))
      })
      this.stage_list.map(async item => {
        if (parseFloat(item.price) < 0) {
          num = true
          console.log(num, 2)
        }
        await gradePrice.push(parseFloat(item.price))
      })
      this.teacher_list.map(async item => {
        if (parseFloat(item.price) < 0) {
          num = true
          console.log(num, 3)
        }
        await levelPrice.push(parseFloat(item.price))
      })
      if (num) {
        this.$message({
          message: '检测到数值异常',
          type: 'warning'
        })
        return
      }
      let res = await updateCoursePricing({
        init_price: initPrice,
        grade_price: gradePrice,
        level_price: levelPrice
      })
      if (res[0]) {
        return
      }
      this.$message({
        message: '保存成功',
        type: 'success'
      })
      this.isSave = !this.isSave
      this.getTableSelete()
    },
    save () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$refs.ruleForm.clearValidate()
          // 保存接口
          this.savequery()
          /// 重新算表格
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0) {
        if (row.count === 0) {
          return {
            rowspan: 0,
            colspan: 0
          }
        } else {
          return {
            rowspan: row.count,
            colspan: 1
          }
        }
      }
    }
  }
}
</script>
<style scoped>
.m-h2-btn-box {
  display: flex;
  justify-content: space-between;
}
.m-form-box {
  min-height: 300px;
}
.u-b-title {
  padding: 30px;
}
.grid-content {
  padding-top: 20px;
}
.u-add-btn {
  font-size: 22px;
  transform: scale(0.6);
}
.z-flex {
  display: flex;
  justify-content: space-between;
}
.u-delete-box {
  margin-left: 20px;
  font-size: 16px;
}
.el-icon-delete {
  cursor: pointer;
}
</style>
